#!/usr/local/bin/python

#http://docs.python.org/library/curses.html
#http://docs.python.org/howto/curses.html

from os import system
import os,curses, time
from player import Player

"""
screens = {0 : {1:"Library", 2:"Add to Library", 3:"Browse", 4:"About", 5:"Exit"},
		   1 : {6:"Artist", 7:"Albums", 8:"Songs", 9:"Genre", 10:"Back"},
		   2 : {11:"Add File", 12:"Add Folder", 13:"Back"},
		  }
"""
class View:
	"""Dibuja pantallas con curses"""
	
	def __init__(self):
		self.__screen = curses.initscr()
		curses.start_color()
		
		curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_GREEN)
		curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLUE)
		curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_RED)
		
	def __get_time(self):
		horaFormato = time.ctime(time.time())
		daystr, month, day, hour, year = horaFormato.split(" ")
		return hour[0:5] + "  " + day + "-" + month + "-" + year
		
	def __get_optline(self, label):
		height, width = self.__screen.getmaxyx()
		label = label[0:width-10]
		return " " + label + " "*(width-6-len(label)) + "> "
		
	def __get_subtitle(self, label):
		height, width = self.__screen.getmaxyx()
		if (len(label) > width - 4):
			label = label[0:width-10] + "..."
		return " " + label + " "*(width-4-len(label))
		
	def __get_title(self, title):
		height, width = self.__screen.getmaxyx()
		w = width - len(title)
		w = w / 2
		return " "*(w-2) + title + " "*(width-w-len(title)-1)
		
	def draw_screen(self, options, activeOpt):
		self.__screen.clear()
		self.__screen.border(0)
		
		self.__screen.addstr(1, 2, self.__get_title("> Cacahuate Music Player <"), curses.color_pair(3))
		self.__screen.addstr(2, 2, self.__get_subtitle(" Home"), curses.color_pair(1))
		
		height, width = self.__screen.getmaxyx()
		initLine = 3
		for pos in range(0, len(options)):
			option = options[pos]
			if (activeOpt == pos):
				self.__screen.addstr(initLine, 2, self.__get_optline(option[1]),curses.color_pair(2))
			else:
				self.__screen.addstr(initLine, 2, self.__get_optline(option[1]))
				
			initLine += 1

		self.__screen.refresh()
		
	def draw_dir(self, options, activeOpt, begin, end, actual_path):
		self.__screen.clear()
		self.__screen.border(0)
		
		self.__screen.addstr(1, 2, self.__get_title("> Cacahuate Music Player <"), curses.color_pair(3))
		self.__screen.addstr(2, 2, self.__get_subtitle(" Home >> Browse: " + actual_path), curses.color_pair(1))
		
		height, width = self.__screen.getmaxyx()
		initLine = 3
		activepos = activeOpt - begin
		for pos in range(0, len(options)):
			option = options[pos]
			if (activepos == pos):
				self.__screen.addstr(initLine, 2, self.__get_optline(option[0:width-5]),curses.color_pair(2))
			else:
				self.__screen.addstr(initLine, 2, self.__get_optline(option[0:width-5]))
				
			initLine += 1

		self.__screen.refresh()
		
	def getch(self):
		return self.__screen.getch()
		
	def height(self):
		height, width = self.__screen.getmaxyx()
		return height - 4
		
	def end(self):
		curses.endwin()
		


class Controlador:
	
	def __init__(self):
		self.view = View()
		self.breadcrumb = []
		self.screens = {0 : [(1,"Library", self.library), (2, "Add to Library", self.add_to_library), (3, "Browse", self.browse), (4, "About", self.about), (5, "Exit", self.exit)],
						1 : [(6, "Artist", self.artist), (7, "Albums", self.albums), (8, "Songs", self.songs), (9, "Genre", self.genre), (10, "Back", self.back)],
						2 : [(11, "Add File", self.add_file), (12, "Add Folder", self.add_folder), (13, "Back", self.back)]
					  }
					  
		self.supported_type = [".mp3", ".ogg"]	
		
	def library(self):
		return 0
		
	def add_to_library(self):
		return 0
		
	def about(self):
		return 0
		
	def exit(self):
		return 0
		
	def artist(self):
		return 0
		
	def albums(self):
		return 0
		
	def songs(self):
		return 0
		
	def genre(self):
		return 0
		
	def back(self):
		return 0
		
	def add_file(self):
		return 0
		
	def add_folder(self):
		return 0
		
	
	def main(self, pos = 0):
		x = 0
		while x != ord('d'):
			self.view.draw_screen(self.screens[0], pos)
			x = self.view.getch()

			if (x == ord('s')):
				pos += 1
				if (pos >= len(self.screens[0])):
					pos = len(self.screens[0]) - 1
			elif (x == ord('w')):
				pos -= 1
				if (pos < 0):
					pos = 0
			
			self.view.end()
			
		#presionaron 'd'
		return pos
		
	
	def __listdir(self, path):
		l = [f for f in os.listdir(path) if (f[0] != "." and 
		(os.path.isdir(os.path.join(path, f)) or 
		(os.path.splitext(f)[1] in self.supported_type)))]
		
		l.sort()
		return l
		
	def is_supported(self, path):
		return os.path.splitext(path)[1] in self.supported_type;
			
			
	
	def browse(self, pos = 0):
		player = Player()
		x = 0
		path = os.path.expanduser("~")
		listdir = ['..'] + self.__listdir(path)
		begin = 0
		end = self.view.height()
		while x != ord('q'):
			if (pos < begin):
				begin -= 1
				end -= 1
			elif (pos >= end):
				begin += 1
				end += 1
				
			part = listdir[begin:end]
			self.view.draw_dir(part, pos, begin, end, path)
			x = self.view.getch()

			if (x == ord('s')):
				pos += 1
				if (pos >= len(listdir)):
					pos = len(listdir) - 1
			elif (x == ord('w')):
				pos -= 1
				if (pos < 0):
					pos = 0
			elif (x == ord('d')):
				if (os.path.isdir(os.path.realpath(os.path.join(path, listdir[pos])))):
					path = os.path.realpath(os.path.join(path, listdir[pos]))
					listdir = ['..'] + self.__listdir(path)
					begin = 0
					end = self.view.height()
					pos = 0
					
			elif (x == ord('p')):
				sound_path = os.path.realpath(os.path.join(path, listdir[pos]))
				if (self.is_supported(sound_path)):
					if (player.playing()):
						player.stop()
						
					player.load(sound_path)
					player.play()
			
			elif (x == ord('o')):
				if (player.playing()):
					player.stop()
			
			elif (x == ord('u')):
				player.inc_volume()
				
			elif (x == ord('j')):
				player.dec_volume()
				
			self.view.end()
			
		#presionaron 'd'
		return pos

	def start(self):
		self.breadcrumb.append(0)
		activeOptions = self.screens[0]
		x = self.main(0)
		while x != 5:
			opt = activeOptions[x]
			
			x = opt[2](0)
			
		self.view.end()
		
		
		
def main():
	controlador = Controlador()
	controlador.start()
	return 0


if __name__ == '__main__':
	main()

